package 拷贝;
class Money implements Cloneable {//1.实现深拷贝,要让在类里面生成实例的类也要实现Cloneable接口
    public double m =19.9;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
class Person implements Cloneable{//要克隆的话一定要实现这个接口,表面当前类是可以被克隆的
    public String name;
    public int age;
    Money money = new Money();


    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }


    @Override
    protected Object clone() throws CloneNotSupportedException {
        //2.克隆person的时候也要克隆money
        //先克隆一份Person对象
        Person tmp = (Person) super.clone();
        //把当前对象this所指向的money克隆一份
        //最后把tmp里面的money指向克隆出来的money
        tmp.money =  (Money) tmp.money.clone();
        //最后返回tmp
        return tmp;
    }
}
public class Test {
    public static void main(String[] args) throws CloneNotSupportedException {
        Person person1 = new Person("小白",19);
        Person person2 = (Person)person1.clone();//person2接受了temp的值
        System.out.println("person1 "+person1.money.m);
        System.out.println("person2 "+person2.money.m);
        System.out.println("=============");
        person1.money.m = 99.9;
        System.out.println("person1 "+person1.money.m);
        System.out.println("person2 "+person2.money.m);
    }
    public static void main1(String[] args) throws CloneNotSupportedException {
        Person person = new Person("小宝",13);
        Person person1 = (Person) person.clone();//我们此时return 的是object类型,我们此时是另外申请了一片内存空间把person里面的值塞进新的对象里面去
        System.out.println(person1.toString());
        System.out.println(person.toString());
        System.out.println(person.money.m);
        System.out.println(person1.money.m);
        System.out.println("=======");
        person.money.m = 99;
        System.out.println(person.money.m);
        System.out.println(person1.money.m);

    }
}
